<?php
/**
 * Description:'优惠券'
 */
namespace backend\controllers;

use bc\controller\BackendController;
use bc\model\coupons\CouponsModel;
use bc\model\coupons\CouponsUserModel;
use bc\model\ProductModel;
use bc\util\backend\Page;
use common\models\User;
use yii\data\Pagination;

class CouponsController extends BackendController{

    //红包类型文字
    private $type_text=array(
        '1'=>'红包',//
        '2'=>'满减',//
    );
    //发放方式
    private $release_type_text=array(
      '1'=>'代言申请发放',//
      '2'=>'系统发放',//
      '3'=>'自动领取'//
    );

    private $use_status_text=array(
        '0'=>'未使用',//
        '1'=>'已使用',//
        '2'=>'赠送中',//
    );

    //使用范围
    private $use_target_text=array(
      '1'=>'单品',//
      '2'=>'产品组',//
      '3'=>'全场',//
    );

    /**
     * @param $status
     * @param $id
     * Description:检查优惠券的使用状态
     */
    private function status_text($status,$id)
    {
        if($status==1){
            return '已删除';
        }
        if($status==0){
            $result=CouponsModel::findOne(['coupons_id'=>$id]);
            if(empty($result)){
                return '未使用';
            }else{
                return '使用中';
            }
        }
    }


    /**
     * Created by Mr.hu.
     * Description:优惠券列表展示
     */
    public function actionIndex()
    {
        $couponsModel=new CouponsModel();
        $list=$couponsModel->getList(null,$this->get('page',1),self::PAGE_SIZE);
        array_walk($list,function (&$item){
                $item['coupons_type_text']=$this->type_text[$item['coupons_type']];
                $item['coupons_release_type_text']=$this->release_type_text[$item['coupons_release_type']];
                $item['coupons_use_target_text']=$this->use_target_text[$item['coupons_use_target']].':<br>'.$this->getProductNameById($item['coupons_use_target'],$item['product_id']);
                $item['status_text']=$this->status_text($item['is_del'],$item['coupons_id']);
                $item['can_edit']=$this->is_cando_edit($item['coupons_id']);
        });

        $total = $couponsModel->getTotal();
        $pagination = new Page($total, self::PAGE_SIZE);
        return $this->render('index',array('list'=>$list,'page'=>$pagination));
    }

    /**
     * Created by Mr.hu.
     * @param $coupon_id
     * Description:是否可以编辑
     */
    private function is_cando_edit($coupon_id)
    {
        return CouponsUserModel::findOne(['coupons_id'=>$coupon_id])?false:true;
    }

    /**
     * Created by Mr.hu.
     * Description:优惠券的添加
     */
    public function actionAdd()
    {
        //产品列表
        $product_list=(new ProductModel())->getProductInfo();
        //产品分组列表
        $product_group_list=array();

        return $this->render('add',['product_list'=>$product_list,'product_group_list'=>$product_group_list]);
    }


    /**
     * Created by Mr.hu.
     * Description:优惠券的编辑
     */
    public function actionEdit()
    {
        $couponsModel=new CouponsModel();
        $coupons_id=$this->get('id',0);
        $info=$couponsModel->getRowById($coupons_id);
        //产品列表
        $product_list=(new ProductModel())->getProductInfo();
        //产品分组列表
        $product_group_list=array();
        $view_data=[
            'product_list'=>$product_list,
            'product_group_list'=>$product_group_list,
            'info'=>$info,
        ];
        return $this->render('edit',$view_data);
    }


    /**
     * Created by Mr.hu.
     * Description:优惠券的添加逻辑处理
     */
    public function actionDealAdd()
    {
        $couponsModel=new CouponsModel();
        $params=$this->post();
        if($couponsModel->_self_validate('add',$params)){
            $data=$couponsModel->create_data;
            $insert_result=$couponsModel->add($data);
            if($insert_result){
                exit(json_encode(array('status'=>1,'msg'=>'添加成功','url'=>'/coupons/add'),0));
            }else{
                exit(json_encode(array('status'=>0,'msg'=>'添加失败'),0));
            }
        }else{
            exit(json_encode(array('status'=>0,'msg'=>$couponsModel->create_error),0));
        }
    }

    /**
     * Created by Mr.hu.
     * Description:优惠券的编辑
     */
    public function actionDealEdit()
    {
        $couponsModel=new CouponsModel();
        $params=$this->post();
        if($couponsModel->_self_validate('edit',$params)){
            $data=$couponsModel->create_data;
            $id=$this->post('coupons_id');
            $insert_result=$couponsModel->modify($data,$id);
            if($insert_result){
                exit(json_encode(array('status'=>1,'msg'=>'修改成功','url'=>'/coupons/index'),0));
            }else{
                exit(json_encode(array('status'=>0,'msg'=>'修改失败'),0));
            }
        }else{
            exit(json_encode(array('status'=>0,'msg'=>$couponsModel->create_error),0));
        }
    }

    /**
     * Created by Mr.hu.
     * Description:优惠券的删除
     */
    public function actionDel()
    {
        $couponsModel=new CouponsModel();
        $coupons_id=$this->get('id');
        if($couponsModel->modify(array('is_del'=>1),$coupons_id)){
            $this->success('删除成功');
        }else{
            $this->error($couponsModel->create_error);
        }
    }

    /**
     * Created by Mr.hu.
     * Description:发放优惠券展示页面
     */
    public function actionIssue()
    {
        //优惠券的id
        $coupons_id=$this->get('id');

        $coupons_info=CouponsModel::find()
        ->select('coupons_name,coupons_id,is_del,release_start_time,release_end_time')
        ->where('coupons_id=:id',[':id'=>$coupons_id])
        ->asArray()
        ->one();
        //检查优惠券是否已经删除
        if($coupons_info['is_del']==1){
            die('<script>alert("该优惠券已删除，请返回重新选择");window.history.go(-1);</script>');
        }
        //检查发放时间是否正确
        $now_time=date('Y-m-d H:i:s');
        if($coupons_info['release_start_time']<$now_time &&$now_time<$coupons_info['release_end_time']){}else{
           die('<script>alert("发放时间有误，请查看发放时间");window.history.go(-1);</script>');
        }

        $assign_date=array(
          'coupons_info'=>$coupons_info,
        );
        return $this->render('issue',$assign_date);
    }

    /**
     * Created by Mr.hu.
     * Description:获取用户列表
     */
    public function actionUserList()
    {
        $mobile=$this->post('mobile','');
        $nickname=$this->post('nickname','');
        $query=User::find()
            ->from('ecs_users as ecu')
            ->innerJoin('bc_wx_user as wu','wu.openid=ecu.wxid');
        $query->where('1=1');
        if($mobile){
            $query->andwhere(array('ecu.mobile'=>$mobile));
        }
        if($nickname){
            $query->andWhere(array('like','wu.nickname',$nickname));
        }
        $list=$query->select('wu.nickname as nicheng,ecu.mobile,ecu.user_id')->createCommand()->queryAll();
        $this->success($list);
    }


    /***
     * Created by Mr.hu.
     * Description:添加优惠券的处理
     */
    public function actionIssueDeal()
    {
        $Model=new CouponsUserModel();
        $data=$this->post();
        $create_validate_data=$Model->self_validate($data);
        if(!$create_validate_data){
            $this->error($Model->_error_message);
        }

        //生成优惠券
        $make_result=$Model->make_coupons();
        if($make_result){
            $this->success('优惠券已生成','/coupons/index');
        }else{
            $this->error('优惠券添加失败');
        }
    }



    /**
     * Created by Mr.hu.
     * Description:针对莫一种优惠券的列表信息
     */
    public function actionCouponsList()
    {
        $coupons_id=$this->get('id',0);
        $couponsUserMode=new CouponsUserModel();
        $coupons_name=CouponsModel::find()->where(array('coupons_id'=>$coupons_id))->select('coupons_name')->one();
        $coupons_name=$coupons_name['coupons_name'];
        $page=$this->get('page',1);
        $list=$couponsUserMode->getCouponsListById($coupons_id,$page,self::PAGE_SIZE);
        array_walk($list,function (&$item){
            $item['mobile']=$this->getUserFieldById($item['user_id'],'mobile');
            $item['status_text']=$this->use_status_text[$item['status']];
        });
        $total = $couponsUserMode->find()->where(['coupons_id'=>$coupons_id])->count();
        $pagination = new Page($total, self::PAGE_SIZE);
        return $this->render('couponslist',['list'=>$list,'pagination'=>$pagination,'coupons_name'=>$coupons_name]);
    }


    /**
     * Created by Mr.hu.
     * @param $user_id
     * @param $field 字符串类型的字段
     * Description:
     */
    private function getUserFieldById($user_id,$field)
    {
        $hash_key=md5('getUserNameById'.$user_id.'--'.$field);
        $cacheMode=\Yii::$app->cache;
        if($return_data=$cacheMode->get($hash_key)){
            return $return_data;
        }else{
            $data=User::find()->from('ecs_users')->where(array('user_id'=>$user_id))->select($field)->one();
            if($data){
                $cacheMode->set($hash_key,$data[$field],3600);
                return $data[$field];
            }
        }

    }


    /**
     * Created by Mr.hu.
     * @param int $type 商品的使用范围
     * @param $product_id 商品的id
     * Description：获取商品名称
     */
    private function getProductNameById($type=1,$product_id)
    {
        switch ($type){
            case 1:
                $info=ProductModel::findOne(['product_id'=>$product_id]);
                return $info['product_name'];
                break;
            case 2:

                break;
        }

    }


}